<?php
require_once 'z.php';
require_once APPLICATION_PATH . '/modules/loan/models/Loans.php';
require_once APPLICATION_PATH . '/modules/loan/models/LoanStatusChanges.php';
require_once APPLICATION_PATH . '/modules/loan/models/LoanWriteOffCharges.php';
require_once APPLICATION_PATH . '/modules/loan/models/LoanWriteOffPayments.php';
require_once APPLICATION_PATH . '/modules/loan/models/Payments.php';


$db = Zend_Db_Table_Abstract::getDefaultAdapter();

$activeLoans = new Zend_Db_Table(array('name' => 'active_loans', 'primary' => 'LoanId'));
$loans = new Zend_Db_Table(array('name' => 'loans', 'primary' => 'LoanId'));
$vloans = new Zend_Db_Table(array('name' => 'view_loans', 'primary' => 'LoanId'));
$loanStatusChanges = new Zend_Db_Table(array('name' => 'loan_status_changes', 'primary' => 'Id'));
$payments = new Zend_Db_Table(array('name' => 'payments', 'primary' => 'LoanId'));
$savingsTransactions = new Zend_Db_Table(array('name' => 'savings_transactions', 'primary' => 'SavingsTransactionId'));
$savingsAccounts = new Zend_Db_Table(array('name' => 'view_savings_accounts', 'primary' => 'SavingsAccountId'));

$data = $vloans->fetchAll($vloans->select()
        ->where('Status = "Disbursed"')
        ->where('CurrentDate >= NextPaymentDate')//->limit(10)
        ->order('LoanId'));
$i = 0;
$j = 0;
foreach($data as $row) { 
    $db->beginTransaction();
    try {
        $i++;
        $plan = new Emms_PmtPlan(new Emms_Loan($row->LoanId));
        $activeLoanUpdate = false;
        foreach($plan->getSchPmtObj() as $schPayment) {
            if($schPayment->Paid) continue;
            if($schPayment->Date > date('Y-m-d')) break;
            $account = $savingsAccounts->find($row->ClientId)->current();
            if(is_null($account->Balance)) break;
            if($account->Balance < $schPayment->Pmt) break; 
            $j++;
            $savingsTransactions->insert(array(
                'Type' => 'Loan Payment',
                'ClientId' => $account->ClientId,
                'LoanId' => $row->LoanId,
                'Date' => date('Y-m-d'),
                'Amount' => $schPayment->Pmt,
                'Balance' => $account->Balance - $schPayment->Pmt,
                'AccruedInterest' => 0,
                'UserId' =>  1,
                'Comments' => '',
                'LastEditDate' => date('Y-m-d H-i-s'),
                'LastEditUserId' => 1
            ));
            $payments->insert(array(
                'LoanId' => $row->LoanId,
                'Date' => date('Y-m-d'),
                'Pmt' => $schPayment->Pmt,
                'Penalties' => $schPayment->Penalties,
                'Delay' => $schPayment->Delay,
                'Interest' => $schPayment->Interest,
                'LoanInsurance' => $schPayment->LoanInsurance,
                'HealthInsurance' => $schPayment->HealthInsurance,
                'AdministrativeFee' => $schPayment->AdministrativeFee,
                'Principal' => $schPayment->Principal,
                'BalancePrincipal' => $schPayment->BalancePrincipal,
                'BalanceLoanInsurance' => $schPayment->BalanceLoanInsurance,
                'BalanceHealthInsurance' => $schPayment->BalanceHealthInsurance,
                'BalanceAdministrativeFee' => $schPayment->BalanceAdministrativeFee,
                'Special' => 0,
                'UserId' => 1,
                'LastEditDate' => date('Y-m-d H-i-s'),
                'LastEditUserId' => 1
            ));
            $activeLoanUpdate = true;
            $activeLoanData = array(
                'BalancePrincipal' => $schPayment->BalancePrincipal,
                'BalanceLoanInsurance' => $schPayment->BalanceLoanInsurance,
                'BalanceHealthInsurance' => $schPayment->BalanceHealthInsurance,
                'BalanceAdministrativeFee' => $schPayment->BalanceAdministrativeFee,
                'PreviousPaymentDate' => $schPayment->Date
            );
        }
        if($activeLoanUpdate) {
            $whereLoans = $loans->getAdapter()->quoteInto('LoanId = ?', $row->LoanId);
            $whereActiveLoans = $activeLoans->getAdapter()->quoteInto('LoanId = ?', $row->LoanId);
            if($activeLoanData['BalancePrincipal'] > 0) {
                $activeLoans->update($activeLoanData + array(
                    'NextPaymentDate' => $schPayment->Date,
                    'ExpectedPaymentAmount' => $schPayment->Pmt,
                    'CurrentDelay' => $schPayment->Delay,
                    'CurrentPenalties' => $schPayment->Penalties
                ), $whereActiveLoans);
            } else {
                $activeLoans->delete($whereActiveLoans);
                $loanStatusChanges->insert(array(
                    'LoanId' => $row->LoanId,
                    'PreviousStatus' => 'Disbursed',
                    'Status' => 'Paid',
                    'Date' => date('Y-m-d'),
                    'Datetime' => date('Y-m-d H-i-s'),
                    'UserId' => 1,
                    'Comments' => ''
                ));
                $loans->update(array(
                    'Status' => 'Paid',
                    'LastEditDate' => date('Y-m-d H-i-s'),
                    'LastEditUserId' => 1
                ), $whereLoans);
            }
        }
    } catch (Zend_Exception $e) {
        $db->rollBack();
        echo $e->getMessage();
        exit;
    }
    $db->commit();
} 
//echo 'Loans: '. $i . PHP_EOL . 'Payments: ' . $j . PHP_EOL; 
//print_r((array)$payment);exit;
//$key = key($sch);

